local cache_r = require "cache"
local cookiePassport = 'x-ienterprise-passport'
local expireCookieTail = '--n'
local ck = require "cookie"

local _M = {}

_M.cache_r = cache_r
_M.cookiePassport = cookiePassport
_M.expireCookieTail = expireCookieTail
_M.ck = ck
_M.cache = cache_r:new()
_M.beta_tenant_ids_key = ngx.var.redis_region .. '_' .. ngx.var.beta_tenant_ids

_M.getCookie = function(self, key)
  local ck = self.ck
  local cookie, err = ck:new()
  if not cookie then
    ngx.log(ngx.ERR, err)
    return
  end
  local cookieValue = tostring(cookie:get(self.cookiePassport))
  --手机端传来的cookieValue带引号，故
  local index, _ =  string.find(cookieValue, "\"")
  if index == 1 then 
    cookieValue = string.sub(cookieValue, 2, -2)
  end
  return cookieValue
end


_M.getBetaTenantIds = function(self)
  local betaTenantIdStr = self.cache:get(self.beta_tenant_ids_key)
    
  local betaTenantIds = {}
  for v in (betaTenantIdStr .. ';'):gmatch('([^;]*);') do
    table.insert(betaTenantIds, v)
  end
  return betaTenantIds
end

_M.changBackend = function(self, tenantId)
  local betaTenantIds = self:getBetaTenantIds()
  for k, v in pairs(betaTenantIds) do
    if v == tenantId then
      ngx.var[ngx.var.backend_key] = ngx.var[ngx.var.backend_key_beta]
      ngx.log(ngx.ERR, "*******************************************start***********************************************************************")
      ngx.log(ngx.ERR, "************************" ..  tenantId .. " shunt to " .. ngx.var[ngx.var.backend_key] .. "****************************")
      ngx.log(ngx.ERR, "*********************************************end***********************************************************************")
      break;
    end
  end
end


_M.shunt = function(self)
  --需要在登录时存储cookie与租户的关系，故而在登录时分流到新版本
  local isLogin = string.find(ngx.var.uri, "/global/login") or string.find(ngx.var.uri, "/global/tenant%-login") or string.find(ngx.var.uri, "/global/logout%-system") or string.find(ngx.var.uri, "/global/do%-login") or string.find(ngx.var.uri, "/global/login%-entry")
  local isTenantLogin = string.find(ngx.var.uri, "/global/login%-entry") or string.find(ngx.var.uri, "/global/tenant%-login")
  local isUserPassLogin = string.find(ngx.var.uri, "/mobile/global/login") or string.find(ngx.var.urii, "")
  --选择租户登录
  if isTenantlogin then 
    local postArgs = ngx.req.get_post_args()
    local tenantId = postArgs.tenantId
    self:changBackend(tenantId)
  elseif 
  if isLogin then
    local mysql = require "mysql_util"
    local sql = "select id"
    local db = mysql:query(sql) 
    ngx.var[ngx.var.backend_key] = ngx.var[ngx.var.backend_key_beta]
  else 
    local cookiePassport = self.cookiePassport
    local cookieValue = self:getCookie(cookiePassport)
    tenantIdKey = ngx.var.redis_region .. "_" .. cookieValue
    --ngx.log(ngx.ERR, "&&&&&&&&&&&&&&&&&&&&tenantIdKey is :" .. tenantIdKey)
    local tenantId = self.cache:get(tenantIdKey)
    self:changBackend(tenantId)
  end
end

_M.exceptionHandler = function(errMsg)
 local errStr = debug.traceback(tostring(errMsg), 6)
  ngx.log(ngx.ERR,"---------------------------error start-------------------------------------")
  ngx.log(ngx.ERR, errStr)
  ngx.log(ngx.ERR,"---------------------------error end-------------------------------------")
end

xpcall(_M.shunt, _M.exceptionHandler, _M)

